Demonstrates cloning by modifying a copy without affecting original
Demonstrates shallow copy by modifying objects that affect both arrays
Apply mathematical operations to every element in the array
Automatically reshapes 1D array to optimal 2D matrix
Creates array with random positive and negative numbers
Automatically rotates array if needed, then finds smallest element
Formula: a, a+d, a+2d, ..., a+(n-1)d
Formula: a, ar, ar², ..., arⁿ⁻¹
Sorts the array using in-place merge sort algorithm with detailed visualization
Sort array using only prefix flips (reverse from index 0 to k)
Sort array such that nums[0] < nums[1] > nums[2] < nums[3]...
Sorts only the specified subarray range
Leave indices empty to fill entire array
Subarrays Results
Total Subarrays
0
Apply mathematical functions to all array elements
Calculates trigonometric functions for each element (in radians)
Delete element and shift all subsequent elements left
Find kth smallest element in sorted array or kth largest in unsorted array
Array will be automatically sorted if needed
Array will be automatically rotated and sorted if needed
Use 'arr' to represent array elements. Examples: arr%2==0 (even), arr!=0 (non-zero), arr<5 (less than 5)
Array should contain numbers from 1 to n with one missing and one repeated
Calculate max(|A[i] - A[j]| + |i - j|) for all i, j
Count unique pairs (i,j) where |arr[i]-arr[j]| = K
Search results will appear here
Linear Search Algorithm
Linear search checks each element in the array sequentially until the target is found or the end is reached.
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // Found at index i
}
}
return -1; // Not found
}
Step 1: Start from the first element (index 0)
Step 2: Compare current element with target
Step 3: If match found, return current index
Step 4: Move to next element and repeat Step 2
Step 5: If end of array reached, element not found
Binary Search Algorithm
Binary search works on sorted arrays by repeatedly dividing the search interval in half.
function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
Step 1: Ensure array is sorted (sort if needed)
Step 2: Set left=0, right=array.length-1
Step 3: Calculate mid = (left + right) / 2
Step 4: Compare element at mid with target
Step 5: If match found, return mid index
Step 6: If target > mid, search right half (left = mid+1)
Step 7: If target < mid, search left half (right = mid-1)
Step 8: Repeat until found or search space exhausted
Count Pairs with Difference K Algorithm
This algorithm counts all unique pairs (i,j) where i < j and |arr[i]-arr[j]| = K.
function countPairsWithDifferenceK(arr, k) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (Math.abs(arr[i] - arr[j]) === k) {
count++;
}
}
}
return count;
}
Step 1: Start with i=0, j=i+1
Step 2: Calculate |arr[i]-arr[j]|
Step 3: If difference equals K, count as valid pair
Step 4: Increment j until end of array
Step 5: Increment i and repeat from Step 2
Step 6: Return total count of valid pairs
Search in Rotated Sorted Array Algorithm
This algorithm searches for an element in a sorted array that has been rotated at some pivot point.
function searchRotatedSorted(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
// Check which half is sorted
if (arr[left] <= arr[mid]) {
// Left half is sorted
if (arr[left] <= target && target < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
// Right half is sorted
if (arr[mid] < target && target <= arr[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
Step 1: Find mid index of current search space
Step 2: Check if mid element equals target
Step 3: Determine which half is properly sorted
Step 4: Check if target lies within the sorted half
Step 5: Adjust search boundaries based on sorted half analysis
Step 6: Repeat until found or search space exhausted
Comparison Search Algorithms
Find First Element > x:
function findFirstGreater(arr, x) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] > x) {
return i; // Found at index i
}
}
return -1; // Not found
}
Find Last Element < x:
function findLastLess(arr, x) {
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] < x) {
return i; // Found at index i
}
}
return -1; // Not found
}
Range Calculation Algorithm (Linear Scan)
This algorithm finds the minimum and maximum elements in an array using a single pass, then calculates the range as max - min.
function findRange(arr) {
if (arr.length === 0) return 0;
let min = arr[0];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
return max - min;
}
Step 1: Initialize min and max with first element
Step 2: Iterate through remaining elements
Step 3: Update min if current element is smaller
Step 4: Update max if current element is larger
Step 5: Calculate range = max - min
Complexity: Time: O(n), Space: O(1)
Find maximum sum of any contiguous subarray of length k
Find longest subarray with sum ≤ target
Group array elements into intervals for histogram analysis
Find maximum/minimum sum of k consecutive elements
Function should take an array and return a single value
Sort array containing only 0s, 1s, and 2s using three-pointer technique
Find all contiguous subarrays with product less than k
Find minimum swaps to group all elements ≤ K together
Find elements that are greater than all elements to their right
Find element that appears more than n/2 times
Find index where sum of left elements equals sum of right elements
Calculate Greatest Common Divisor and Least Common Multiple
Identify prime numbers (green) and composite numbers (red) in the array
Equilibrium Point Algorithm
An equilibrium point is an index in the array where the sum of elements on the left equals the sum of elements on the right.
function findEquilibrium(arr) {
let totalSum = arr.reduce((a, b) => a + b, 0);
let leftSum = 0;
for (let i = 0; i < arr.length; i++) {
let rightSum = totalSum - leftSum - arr[i];
if (leftSum === rightSum) {
return i; // Equilibrium found
}
leftSum += arr[i];
}
return -1; // No equilibrium point
}
Step 1: Calculate total sum of all elements
Step 2: Initialize left sum to 0
Step 3: For each index i, calculate right sum = total sum - left sum - arr[i]
Step 4: If left sum equals right sum, return current index
Step 5: Otherwise, add current element to left sum and continue
Step 6: If no equilibrium found, return -1
Data Binning Algorithms
Binning by Number of Intervals:
function binByCount(arr, numBins) {
const minVal = Math.min(...arr);
const maxVal = Math.max(...arr);
const range = maxVal - minVal;
const binSize = range / numBins;
const bins = Array(numBins).fill(0).map(() => []);
for (let value of arr) {
const binIndex = Math.min(
Math.floor((value - minVal) / binSize),
numBins - 1
);
bins[binIndex].push(value);
}
return bins;
}
pop() {
if (this.isEmpty()) throw "Stack Underflow";
return this.arr[this.top--];
}
peek() {
if (this.isEmpty()) throw "Stack is Empty";
return this.arr[this.top];
}
}
Find all sequences of consecutive numbers that sum to target
Randomly select an element based on weights using Cumulative Weights method
Uses array elements as center coordinates and radius
Ugly Number Algorithms
Ugly Number Check:
function isUgly(num) {
if (num <= 0) return false;
while (num % 2 === 0) num /= 2;
while (num % 3 === 0) num /= 3;
while (num % 5 === 0) num /= 5;
return num === 1;
}
Nth Ugly Number (Dynamic Programming):
function nthUglyNumber(n) {
let ugly = [1];
let i2 = 0, i3 = 0, i5 = 0;
for (let i = 1; i < n; i++) {
let next = Math.min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5);
ugly.push(next);
if (next === ugly[i2]*2) i2++;
if (next === ugly[i3]*3) i3++;
if (next === ugly[i5]*5) i5++;
}
return ugly[n-1];
}
Super Ugly Number:
function superUglyNumber(n, primes) {
let ugly = [1];
let indices = Array(primes.length).fill(0);
for (let i = 1; i < n; i++) {
let next = Math.min(...primes.map((p, j) => ugly[indices[j]] * p));
ugly.push(next);
primes.forEach((p, j) => {
if (next === ugly[indices[j]] * p) indices[j]++;
});
}
return ugly[n-1];
}
Abbreviation must be alphanumeric (e.g., w3b4j9)
Enter a string containing only + and - characters
Pattern Search Algorithm
Split array into k subarrays to minimize the largest sum
Count subarrays with exactly k distinct integers
Find the longest subarray where comparison signs alternate between elements
Count pairs (i, j) where i < j and nums[i] > 2 * nums[j]
Analyze local and global inversions with step-by-step visualization
Find minimum arrows to burst overlapping balloons (intervals)
Enter building heights to find which buildings have ocean view
Index array size must match values array size
Generate Gray code where successive numbers differ by exactly one bit
Binary search to find smallest divisor where sum of ceil(arr[i]/divisor) ≤ threshold
Higher bit counts will show more detailed visualization
Find minimum capacity to ship all packages within given days
Find minimum eating speed to finish all bananas within given hours
Find the first bad version in [G, G, ..., B, B, ...] array
Maximum sum of non-adjacent elements with DP visualization
Greedy algorithm for the NP-hard Shortest Superstring problem
Find elements that appear once when others appear multiple times
Solve circular route gas station problem
String should contain only 'L' and 'R' characters
Enter a string containing characters 'a', 'b', and 'c'
Count subarrays with exactly k odd numbers
Partition array such that every element in left <= every element in right
Partition array into subarrays of length at most k to maximize sum
Partition string where each character appears in only one partition
Check if array can be split into three contiguous parts with equal sum
Enter strings as JSON array and choose delimiter
Game theory: Can the first player force a win?
String Operations Algorithms
Encode/Decode Strings:
def encode(strs):
if not strs: return ""
encoded = []
for s in strs:
encoded.append(f"{len(s)}#{s}")
return "".join(encoded)
def decode(s):
if not s: return []
res = []
i = 0
while i < len(s):
delimiter_idx = s.find('#', i)
length = int(s[i:delimiter_idx])
i = delimiter_idx + 1
res.append(s[i:i + length])
i += length
return res
Koko Eating Bananas Algorithm
Koko wants to eat all bananas in h hours. Each pile has a different number of bananas. Koko can eat k bananas per hour from any pile. Find the minimum k such that Koko can eat all bananas within h hours.
Algorithm Steps:
function minEatingSpeed(piles, h):
left = 1, right = max(piles)
while left < right:
mid = (left + right) // 2
hours_needed = 0
for pile in piles:
hours_needed += ceil(pile / mid)
if hours_needed <= h:
right = mid // Try smaller speed
else:
left = mid + 1 // Need larger speed
return left
Example:
piles = [3, 6, 7, 11], h = 8
k = 4 → hours = ceil(3/4)+ceil(6/4)+ceil(7/4)+ceil(11/4) = 1+2+2+3 = 8 ✓
k = 3 → hours = ceil(3/3)+ceil(6/3)+ceil(7/3)+ceil(11/3) = 1+2+3+4 = 10 ✗
Minimum k = 4
Step 1: Initialize binary search range [1, max(pile)]
Step 2: Test middle speed k
Step 3: Calculate total hours needed for speed k
Step 4: If hours ≤ h, k is valid → search lower half
Step 5: If hours > h, k is invalid → search upper half
Find maximum sum of contiguous subarray allowing at most one element deletion
Find the longest chain of pairs where b < c in [a,b] and [c,d]
Find all arithmetic subarrays with at least 3 elements
Calculate number of ways to decode a numeric string to letters (A=1, B=2... Z=26)
Check if array can be partitioned into two subsets with equal sum
Check if a string can be segmented into dictionary words
Find maximum subarray sum no larger than K
For Sliding Window Median: Enter window size k between 1 and array length
Visualizes LRU Cache with array + hash map. Press Shift+R to reset.
Visualizes Least Frequently Used (LFU) Cache Algorithm
Decode Ways Algorithm
Counts the number of ways to decode a string of digits to letters using mapping: A=1, B=2, ..., Z=26.
function numDecodings(s) {
if (!s || s[0] == '0') return 0;
let n = s.length;
let dp = new Array(n+1).fill(0);
dp[0] = 1; // empty string
dp[1] = 1; // first digit
for (let i = 2; i <= n; i++) {
let single = parseInt(s[i-1]);
let twoDigit = parseInt(s.substring(i-2, i));
if (single != 0) dp[i] += dp[i-1];
if (10 <= twoDigit <= 26) dp[i] += dp[i-2];
}
return dp[n];
}
LeetCode Problem 1186: Maximum Subarray Sum with One Deletion
Given an array of integers, return the maximum sum of a contiguous subarray (possibly empty)
after deleting at most one element from the array.
def maximumSum(arr):
"""
Given an array of integers, return the maximum sum of a subarray
with at most one element deletion.
Time: O(n), Space: O(n)
"""
n = len(arr)
if n == 0: return 0
if n == 1: return arr[0]
# forward[i]: max subarray sum ending at i
forward = [0] * n
forward[0] = arr[0]
for i in range(1, n):
forward[i] = max(arr[i], forward[i-1] + arr[i])
# backward[i]: max subarray sum starting at i
backward = [0] * n
backward[n-1] = arr[n-1]
for i in range(n-2, -1, -1):
backward[i] = max(arr[i], backward[i+1] + arr[i])
# Option 2: With one deletion
max_with_deletion = float('-inf')
for i in range(1, n-1):
# Delete element at i, connect forward[i-1] and backward[i+1]
max_with_deletion = max(max_with_deletion, forward[i-1] + backward[i+1])
return max(max_no_deletion, max_with_deletion)
# Optimized version with O(1) space
def maximumSumOptimized(arr):
"""Optimized version with O(1) space using DP states."""
dp0 = arr[0] # max sum ending at i with 0 deletions
dp1 = 0 # max sum ending at i with 1 deletion
res = arr[0]
for i in range(1, len(arr)):
# With 1 deletion: either delete current element (dp0)
# or we've already deleted before (dp1 + arr[i])
dp1 = max(dp0, dp1 + arr[i])
# With 0 deletions: standard Kadane
dp0 = max(arr[i], dp0 + arr[i])
res = max(res, dp0, dp1)
return res
Algorithm Explanation
Step 1: Calculate forward maximum subarray sums (Kadane's algorithm from left)
Step 2: Calculate backward maximum subarray sums (Kadane's algorithm from right)
Step 3: For each element (except first and last), calculate sum of forward[i-1] + backward[i+1]
Step 4: Compare with no-deletion maximum and return the maximum of both
Time Complexity: O(n) where n is array length
Space Complexity: O(n) for DP arrays, O(1) for optimized version
Investment Analysis Toolkit
Professional financial metrics for informed investment decisions
💡 Business Context: Enter historical stock prices to analyze investment performance, volatility, and returns.
Day-to-day percentage changes
Continuous compounding returns
Total return from start to each point
Overall investment performance
Daily price movements & volatility
N-day price momentum
ROC percentage indicator
Opening gap calculations
Daily trading performance
SMA - Average price over period
EMA - Weighted average
MACD - Trend momentum
Signal line for MACD
Bollinger Middle Band
Bollinger Upper Band
Key Metrics Explained
Daily Returns: Essential for understanding short-term volatility and daily performance
Log Returns: Used in financial modeling for time-series analysis and risk management
Cumulative Returns: Shows investment growth trajectory over time
Total Return: Overall investment performance measurement
Price Differences: Reveals daily price movements and market volatility patterns
Set operations work with exactly 2 arrays
Set Operations Algorithms
Union of Arrays:
function unionArrays(arrays) {
let unionSet = new Set();
for (let arr of arrays) {
for (let element of arr) {
unionSet.add(element);
}
}
return Array.from(unionSet);
}
Intersection of Arrays:
function intersectionArrays(arrays) {
if (arrays.length === 0) return [];
let intersection = arrays[0];
for (let i = 1; i < arrays.length; i++) {
intersection = intersection.filter(
element => arrays[i].includes(element)
);
}
return [...new Set(intersection)];
}
Solve famous Leetcode array problems with visualizations
Enter a string containing only curly braces {} to validate parentheses
Uses binary search to find first and last occurrence in sorted array
Enter string containing only '(' and ')' characters
Count how many times target string appears as subsequence in main string
Determine if you can reach the last index starting from first index
Find maximum profit from daily stock prices (LeetCode #121)
// Add this in the algorithm explanation section
Best Time to Buy and Sell Stock Algorithm
Find the maximum profit by buying low and selling high. You can only make one transaction.
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (let i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
Step 1: Initialize minPrice to infinity and maxProfit to 0
Step 2: Iterate through each day's price
Step 3: Update minPrice if current price is lower
Step 4: Calculate potential profit and update maxProfit if higher
Step 5: Return the maximum profit found
Find days until warmer temperature for each day
Calculate sum of elements from start to end index (inclusive)
Given a collection of intervals, merge all overlapping intervals
For each element, count how many elements to the right are smaller
Find the length of the longest substring without repeating characters
Longest Substring Results
Longest Substring Length
0
Longest Substring Found
-
Longest Substring Results
Longest Substring Length
0
Longest Substring Found
-
Longest Substring Without Repeating Characters Algorithm
function lengthOfLongestSubstring(s) {
let maxLength = 0;
let start = 0;
let charMap = new Map();
for (let end = 0; end < s.length; end++) {
if (charMap.has(s[end]) && charMap.get(s[end]) >= start) {
start = charMap.get(s[end]) + 1;
}
charMap.set(s[end], end);
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
Algorithm Steps:
Step 1: Initialize start pointer, maxLength, and character map
Step 2: Iterate through string with end pointer
Step 3: If duplicate found within current window, move start pointer
Step 4: Update character's last seen position
Step 5: Update maxLength if current window is longer
Step 6: Return maxLength when iteration completes
Find maximum fruits you can pick with two baskets
Convert array to non-decreasing using Greedy + Prefix Sum approach
Calculate span values using monotonic stack approach
Calculate maximum rectangular area in histogram using stack
Rearranges array into lexicographically next greater permutation
Two Sum Algorithm
Find all pairs of indices where the sum of elements equals the target.
function twoSum(arr, target) {
let pairs = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === target) {
pairs.push([i, j]);
}
}
}
return pairs;
}
Trapping Rain Water:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let water = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left];
left++;
} else {
rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right];
right--;
}
}
return water;
}
Stock Span Problem Algorithm
The stock span problem calculates for each day, the number of consecutive days (including current day)
for which the stock price was less than or equal to the current day's price.
function calculateStockSpan(prices) {
let spans = new Array(prices.length);
let stack = []; // monotonic stack (decreasing order)
for (let i = 0; i < prices.length; i++) {
// Pop while stack is not empty and top <= current
while (stack.length > 0 && prices[stack[stack.length-1]] <= prices[i]) {
stack.pop();
}
// Calculate span
spans[i] = stack.length === 0 ? i + 1 : i - stack[stack.length-1];
// Push current index to stack
stack.push(i);
}
return spans;
}
Key Points:
• Uses a monotonic stack (decreasing order of prices)
• Time Complexity: O(n) - each element pushed and popped once
• Space Complexity: O(n) for the stack
Visualize advanced sorting algorithms with step-by-step animations
Advanced Sorting Algorithms
Selection Sort:
function selectionSort(arr) {
let n = arr.length;
for (let i = 0; i < n-1; i++) {
let minIdx = i;
for (let j = i+1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
}
return arr;
}
Measures research impact based on citation counts
Custom Comparator Sort
Sort Configuration
Dictionary Data
Sorting Process Visualization
Starting custom comparator sort...
Insertion Sort:
function insertionSort(arr) {
let n = arr.length;
for (let i = 1; i < n; i++) {
let key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
return arr;
}
Selection Sort Steps:
• Find the minimum element in the unsorted portion
• Swap it with the first element of the unsorted portion
• Move the boundary between sorted and unsorted portions one element to the right
• Repeat until the entire array is sorted
Insertion Sort Steps:
• Start with the second element as the key
• Compare the key with elements in the sorted portion to its left
• Shift elements greater than the key one position to the right